package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTaskActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProTaskDetailActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProTask;
import com.linkage.jz.bankruptcy.bean.CommonStatusInfo;
import com.linkage.jz.bankruptcy.bean.UserInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * Fragment-任务
 */
public class ProTaskFragment extends Fragment implements View.OnClickListener {
    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";

    private RecyclerView mRecyclerView;
    private TaskAdapter mAdapter;
    private String mProjectId;
    private List<ProTask> mData;
    private TextView task_count;

    private boolean addTask = false;

    public static ProTaskFragment newInstance(int page, String infoid) {
        Bundle args = new Bundle();
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        args.putString("infoid", infoid);
        ProTaskFragment tripFragment = new ProTaskFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        ProDetailActivity parentActivity = (ProDetailActivity) getActivity();
        parentActivity.showLoading();
        getList();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mProjectId = getArguments().getString("infoid");
        mData = new ArrayList<>();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_TASK)) {
            getList();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_detailpro_mission, container, false);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        view.findViewById(R.id.tv_pro_module_item_add).setOnClickListener(this);
        view.findViewById(R.id.ll_pro_module_item_add).setOnClickListener(this);

        task_count= view.findViewById(R.id.task_count);
        initAdapter(mData);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getList();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_pro_module_item_add:
            case R.id.tv_pro_module_item_add:
                Intent intent = new Intent(getActivity(), CreateProTaskActivity.class);
                intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                startActivity(intent);
        }
    }

    private void refreshAction() {
        View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
        View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
        TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
        TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
        TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
        tv_pro_module_nodata_tip.setText("还没有任务记录");
        tv_pro_module_item_add.setText("新建任务");
        tv_pro_module_item_add0.setText("新建任务");

        if (addTask) {
            if (mData.size() > 0) {
                ll_pro_module_item_add.setVisibility(View.VISIBLE);
                area_pro_module_nodata_tip.setVisibility(View.GONE);
                task_count.setVisibility(View.VISIBLE);
            } else {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                tv_pro_module_item_add.setVisibility(View.VISIBLE);
                task_count.setVisibility(View.GONE);
            }
        } else {
            if (mData.size() > 0) {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.GONE);
                task_count.setVisibility(View.VISIBLE);
            } else {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                tv_pro_module_item_add.setVisibility(View.GONE);
                task_count.setVisibility(View.GONE);
            }
        }
         task_count = getView().findViewById(R.id.task_count);
        if (mData.size() > 0) {
            task_count.setVisibility(View.VISIBLE);
            task_count.setText("任务：" + mData.size());
        } else {
            task_count.setVisibility(View.GONE);
        }

    }

    private void initAdapter(List<ProTask> data) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new TaskAdapter(getActivity(), R.layout.fragment_pro_detailpro_mission_item, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);//设置adapter
        //设置item点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()) {
                    case R.id.ll_taskitem:
                        Intent intent = new Intent(getActivity(), ProTaskDetailActivity.class);
                        intent.putExtra(ProTaskDetailActivity.KEY_ID, mData.get(position).getId());
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    class TaskAdapter extends BaseQuickAdapter<ProTask, BaseViewHolder> {
        int mLayoutId;

        public TaskAdapter(Context context, int LayoutId, List<ProTask> str) {
            super(R.layout.fragment_pro_detailpro_mission_item, str);
            Log.e("=========----====talk2", LayoutId + "");
            mLayoutId = LayoutId;
        }

        @Override
        public void convert(BaseViewHolder helper, ProTask info) {

            helper.addOnClickListener(R.id.ll_taskitem);
            helper.setText(R.id.tv_tasktitle, info.getTaskName());

            UserInfo userInfo = info.getExecutor();
            if (userInfo != null) {
                helper.setText(R.id.tv_settinger, "执行人：" + userInfo.getUsername());
            }
            userInfo = info.getCreator();
            if (userInfo != null) {
                helper.setText(R.id.tv_creater, "   创建人：" + userInfo.getUsername());
            }

            helper.setText(R.id.tv_tasktime, "截止时间：" + DateFormatUtils.long2Str(info.getDeadlineTime(), true));

            CommonStatusInfo taskStatusInfo = info.getStatus();
            if (taskStatusInfo != null) {
                if ("2".equalsIgnoreCase(taskStatusInfo.getValue())) {
                    helper.setTextColor(R.id.tv_taskstatus, getResources().getColor(R.color.pro_task_status_ywc));
                } else {
                    helper.setTextColor(R.id.tv_taskstatus, getResources().getColor(R.color.pro_task_status_wcl));
                }
                helper.setText(R.id.tv_taskstatus, taskStatusInfo.getText());
            }

        }
    }


    public void getList() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
//        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null||"".equalsIgnoreCase(userToken)) {
//            View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
//            View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
//            TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
//            TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
//            TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
//            tv_pro_module_nodata_tip.setText("还没有任务记录");
//            tv_pro_module_item_add.setText("新增公示");
//            tv_pro_module_item_add0.setText("新建公示");
//            area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
//            tv_pro_module_item_add.setVisibility(View.GONE);
//            task_count.setVisibility(View.GONE);
//            return;
//        }
        Network
                .getAPIService()
                // TODO 是否是管理员需要动态获取
                .getTaskList(userToken, mProjectId, 0, 1, 100)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null||"".equalsIgnoreCase(userToken)) {
                                View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
                                View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
                                TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
                                TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
                                TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
                                tv_pro_module_nodata_tip.setText("还没有任务记录");
                                tv_pro_module_item_add.setText("新增公示");
                                tv_pro_module_item_add0.setText("新建公示");
                                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                                tv_pro_module_item_add.setVisibility(View.GONE);
                                task_count.setVisibility(View.GONE);
                                return;
                            }
//                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        addTask = data.getAsJsonObject("auth").get("addTask").getAsBoolean();
                        JsonArray arr = data.getAsJsonObject("taskList").getAsJsonArray("list");
                        List<ProTask> list = ProTask.parse(arr);
                        mData.clear();
                        mData.addAll(list);
                        refreshAction();
                        mAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }
}
